<template>
  <div class="detailed-plan">
    <div class="date-time">
      <ElSlider v-model="currentTime" :min="1" :max="24" :step="1" show-stops show-tooltip :marks="marks" @click="choseTime" />
      <!-- <el-slider v-model="currentTime" :min="1" :max="24" :step="2" /> -->
    </div>
    <div class="date-section">
      <div class="date-list">
        <div v-for="date in dates" @click="chooseDate(date)" :key="date" class="date-item" :class="{ active: date === currentDate }">{{ date }}</div>
        <div class="date-item">
          <ElDatePicker
            v-model="customTime"
            type="date"
            :clearable="false"
            placeholder="选择日期"
            popper-class="custom-datepicker-popper"
            @change="changeDate"
          >
          </ElDatePicker>
        </div>
      </div>
    </div>
    <img src="./img/frame.png" style="width: 100%; height: 100%" />
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, ref, onMounted, computed } from "vue"
import useLifecycle from "@mars/common/uses/use-lifecycle"
import * as mapWork from "./map"
import { useWidget } from "@mars/common/store/widget"
import { ElDatePicker, ElSlider, ElLoading } from "element-plus"
import type { LoadingInstance } from "element-plus/es/components/loading/src/loading"
import { parseTime } from "@mars/utils/common"
// 启用map.ts生命周期
useLifecycle(mapWork)
const { disable, currentWidget, disableAll } = useWidget()
const isShow = ref(false)
const dates = ref([])
const currentYear = ref()
const currentDate = ref("1月18日")
const currentTime = ref(2)
const customTime = ref()

const boundarypath: string = import.meta.env.VITE_APP_BOUNDARY_PATH as string
const marks = Array.from({ length: 24 }, (_, i) => i + 1).reduce(
  (acc, hour) => ({
    ...acc,
    [hour]: `${hour}点`
  }),
  {}
)

function generateRecentDates(days = 7) {
  const result = []
  const now = new Date()

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(now.getDate() - i) // 从 days-1 天前到当天

    const month = date.getMonth() + 1 // 月份 (0-11 → 1-12)
    const day = date.getDate()

    result.push(`${month}月${day}日`)
  }

  currentYear.value = now.getFullYear()
  currentDate.value = now.getMonth() + 1 + "月" + now.getDate() + "日"
  currentTime.value = now.getHours() - 2
  customTime.value = now
  return result
}

// 日期格式化函数
function formatDateWithHour(year: string, month: string, day: string, hour: number | string): string {
  let hourNum = Number(hour) - 1 //

  // 处理负数情况（比如 hour 原本是 0，减 1 后变成 -1）
  if (hourNum < 0) {
    hourNum = 0 // 可以设为 0，或者根据需求调整
  }

  const paddedHour = String(hourNum).padStart(2, "0")
  return `${year}-${month}-${day} ${paddedHour}:00:00`
}

// 提取中文日期解析函数
function parseChineseDate(chineseDate: string): { month: string; day: string } {
  const [monthStr, dayStr] = chineseDate.split("月")
  const month = monthStr.padStart(2, "0")
  const day = dayStr.replace("日", "").padStart(2, "0")
  return { month, day }
}

const formattedDateTime = computed(() => {
  try {
    if (customTime.value) {
      const [yearStr, monthStr, dayStr] = parseTime(customTime.value, "{y}-{m}-{d}").split("-")
      return formatDateWithHour(yearStr, monthStr, dayStr, currentTime.value)
    } else {
      const { month, day } = parseChineseDate(currentDate.value)
      return formatDateWithHour(currentYear.value, month, day, currentTime.value)
    }
  } catch (error) {
    console.error("日期格式化错误:", error)
    return "" // 或返回默认值
  }
})


// 创建全局加载实例引用
let loadingInstance: LoadingInstance | null = null

// 显示全屏加载
const showFullscreenLoading = () => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: "",
    background: "rgba(0, 0, 0, 0.7)",
    spinner: "", // 隐藏默认旋转图标
    customClass: "full-custom-loading"
  })
  // 添加自定义HTML
  setTimeout(() => {
    const loadingElement = document.querySelector(".full-custom-loading .el-loading-spinner")
    if (loadingElement) {
      loadingElement.innerHTML = `
        <div style="text-align: center;">
          <div class="custom-spinner">
            <div class="spinner-circle"></div>
            <div class="spinner-text">加载中...</div>
          </div>
        </div>
      `
    }
  }, 50)
}

// 隐藏全屏加载
const hideFullscreenLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

async function chooseDate(date: string) {
  currentDate.value = date
  const { month, day } = parseChineseDate(date)
  customTime.value = formatDateWithHour(currentYear.value, month, day, "00")
  await initMap()
}

async function choseTime(e: any) {
  await initMap()
}

async function changeDate() {
  if (!customTime.value) { return }

  const date = new Date(customTime.value)
  currentDate.value = `${date.getMonth() + 1}月${date.getDate()}日`
  await initMap()
}

async function initMap(addModelFlag = false) {
  try {
    showFullscreenLoading()
    const originalData = formattedDateTime.value.substring(0, 13).replace(" ", "_")
    await Promise.all([
      mapWork.add3DLayer(originalData),
      mapWork.layerManager.addTileLayer(originalData, {
        cropWithGeoJSON: boundarypath,
        flyTo: false
      }),
      mapWork.loadNoiseDataForQX(originalData),
      addModelFlag && mapWork.flyToModel(currentWidget.data.layerId, currentWidget.data.center, originalData)
    ])
  } finally {
    hideFullscreenLoading()
  }
}

onMounted(async () => {
  try {
    showFullscreenLoading()
    dates.value = generateRecentDates()
    await initMap(true)
  } finally {
    hideFullscreenLoading()
  }
})

onUnmounted(() => {
  // 销毁操作
})
</script>
<style lang="less" scoped>
.detailed-plan {
  position: absolute;
  bottom: 10px;
  right: 55px;
  // height: 100%;
  width: 1000px;
}
.date-time {
  width: 100%;
  height: 8px;
  cursor: pointer;

  /* 强制穿透 scoped 样式 */
  ::v-deep .el-slider {
    height: 8px;
  }
  ::v-deep .el-slider__bar {
    background-color: #1281f8 !important;
    height: 8px;
  }
  ::v-deep .el-slider__runway {
    background-color: #f0f0f0 !important;
    height: 8px;
  }

  ::v-deep .el-slider__marks-stop {
    width: 8px;
    height: 8px;
    background-color: #409eff;
    border-radius: 50%;
  }

  ::v-deep .el-slider__marks-text {
    // margin-top: 8px;
    // font-size: 12px;
    color: #f0f0f0;
    transform: translateY(-200%);
  }
}
.date-section {
  margin-top: 3px;
  margin-bottom: 15px;
  width: 100%;
}

.date-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}

.date-list {
  list-style-type: none;
  display: flex;
  justify-content: space-between;
  background-color: #526b85;
  line-height: 30px;
  .date-item {
    font-size: 16px;
    // margin-bottom: 8px;
    position: relative;
    width: 100%;
    text-align: center;
    border-right: 1px solid #f7eeee;
    cursor: pointer;
    &.active {
      background-color: #559de9;
    }
    ::v-deep .el-input {
      width: 100% !important;
    }
    ::v-deep .el-input__wrapper {
      display: flex;
      width: 100% !important;
      .el-input__inner {
        text-align: center;
      }
    }
  }
}
::v-deep .el-picker-panel__body-wrapper {
  .el-picker-panel__body {
    background-color: #409eff !important;
  }
}
</style>
<style>
.custom-datepicker-popper {
  /* 全局样式 */
  .custom-datepicker-popper {
    background: #f5f7fa;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .el-picker-panel__body-wrapper {
    background-color: #f5f7fa !important;
  }
}
/* 自定义加载动画 */
.full-custom-loading .custom-spinner {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}

.full-custom-loading .spinner-circle {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.full-custom-loading .spinner-text {
  color: #fff;
  font-size: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
